class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        TreeNode* cur = root;
        TreeNode* prev = nullptr;
        stack<TreeNode*>st;
        vector<int>s;
        while (cur || !st.empty())
        {
            while (cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* temp = st.top();
            if (temp->right == nullptr || prev == temp->right)
            {
                st.pop();
                s.push_back(temp->val);
                prev = temp;
            }
            else
            {
                cur = temp->right;
            }
        }
        return s;
    }
};
